//
//  ViewController.m
//  相片相机
//
//

#import "postPicViewController.h"
#import "PhotoViewController.h"
#import "SelectedCell.h"
#import "NetRequest.h"
#import "ZMView.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "TZImagePickerController.h"
#import "SDDemoItemView.h"
#import "SDBallProgressView.h"

#import "EducationAdminClient_URL.h"

#import "RecordHUD.h"
#import "D3RecordButton.h"//录音按钮

#import "MSSBrowseDefine.h"
#import "UIImageView+WebCache.h"
//#import "MSSCollectionViewCell.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height




@interface postPicViewController ()<TZImagePickerControllerDelegate,UINavigationControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIImagePickerControllerDelegate,UITextViewDelegate>
{
    TZImagePickerController *imagePickerVc;
    float sss;
}
@property (nonatomic, strong) NSMutableArray *demoViews;

@property (nonatomic, strong) SDDemoItemView *demoView;

@property(nonatomic,strong)NSMutableArray *imagePaths;

@property (nonatomic,strong)UITextView * MsTextView;

@property (nonatomic,strong)UIButton * addButton;

@property (nonatomic,strong)UICollectionView * cv;//照片

@property (nonatomic,strong)UITableView *tv;//音频

@property (nonatomic,strong)UIView * background;

@property (nonatomic,copy)NSString *picString;

@property (nonatomic,copy)NSString *voiceString;

@property(nonatomic,strong)NSMutableArray *picArr;

@property(nonatomic,strong)NSMutableArray *voiceArr;

@property(nonatomic,strong)NSMutableArray *voiceDataArr;

@property(nonatomic,strong)UILabel *la;

@property(nonatomic,strong)NSTimer *timer;

@property(nonatomic,assign)BOOL ifFirst;

@property(nonatomic,strong) D3RecordButton *voiceBtn;//音频按钮

@property(nonatomic,strong)UIImageView *voiceView;//音频背景
@property(nonatomic,strong)UIImageView *voiceimg;//声音图片
@property(nonatomic,strong)UIImageView *voiceAnim;//音频动画
@property(nonatomic,strong)UILabel *timela;//音频时间
@property(nonatomic,strong)UIButton *deleVoice;//删除音频
@property(nonatomic,assign)float voicesecond;
@property(nonatomic,assign)BOOL ifVoicing;
@property(nonatomic,strong)NSMutableArray *smallUrlArray;

@property(nonatomic,strong) UIButton *voiceBackBtn;

@property(nonatomic,strong)NSData *voicedata;

@property (nonatomic ,copy)NSString *amrPath;
@property (nonatomic ,copy)NSString *wavPath;
@property (nonatomic ,assign)BOOL imageArrCountFall;//数组是否装满

@property (nonatomic, assign)NSInteger fallfileCount;//失败文件个数

@property (nonatomic, assign)BOOL   ZJXDB;//是否是点击相册，如果点击相册需要添加图片

//@property(nonatomic,strong)MBProgressHUD *HD;

@end

@implementation postPicViewController

static int a;
-(NSMutableArray *)voiceDataArr{
    if(_voiceDataArr ==nil){
        _voiceDataArr = [NSMutableArray array];
    }
    return _voiceDataArr;
}

- (NSMutableArray *)demoViews
{
    if (_demoViews == nil) {
        _demoViews = [NSMutableArray array];
    }
    return _demoViews;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    BOOL is  = [self isVisible];
    if(!is){
        a=0;
        if(_imageMongoArr.count>0){
            [self.imgArr removeAllObjects];
            [self loadPic];
        }else if (_mp3MongoArr.count>0){
            _voiceView.hidden = YES;
            [self loadVoice];
        }
    }
    
}

-(NSMutableArray *)failedSaveCountArray{
    if (!_failedSaveCountArray) {
        _failedSaveCountArray = [[NSMutableArray alloc] init];
    }
    return _failedSaveCountArray;
}

-(BOOL)isVisible{
    return (self.isViewLoaded&&self.view.window);
}

-(void)loadVoice{
    NSString *str = _mp3MongoArr[0];
    NSString *requestURL =[NSString stringWithFormat:@"%@%@",self.programaUrl,GETPIC];
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    [params setObject:str forKey:@"str"];
    
    
    _ZJXDB = NO;
    [NetRequest requestUrl:requestURL andParamas:params andReturnBlock:^(NSData *data, NSError *error) {
        if(data&&!error){
            _voiceView.hidden = NO;
            _voicedata = data;
            
            
        }else{
            
        }
    }];
}

-(void)loadPic{
    
    NSString *str = _imageMongoArr[a];
    NSString *requestURL =[NSString stringWithFormat:@"%@%@",self.programaUrl,GETPIC];
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    [params setObject:str forKey:@"str"];
    
    
    [NetRequest requestUrl:requestURL andParamas:params andReturnBlock:^(NSData *data, NSError *error) {
        if(data&&!error){
            UIImage *image=[UIImage imageWithData:data];
            if(image==nil){
                return ;
            }
            [self.imgArr addObject:image];
            a++;
            if(a<_imageMongoArr.count){
                [self loadPic];
                [self.cv reloadData];
            }else{
                [self.cv reloadData];
                if(_mp3MongoArr.count>0){
                    [self loadVoice];
                }
            }
        }else{
            
        }
    }];
    
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

//-(void)addProgressFrame{
//    [self.demoViews addObject:[SDDemoItemView demoItemViewWithClass:[SDBallProgressView class]]];
//    [self.demoViews enumerateObjectsUsingBlock:^(SDDemoItemView *demoView, NSUInteger idx, BOOL *stop) {
////        [self.view addSubview:demoView];
//        NSArray *arr = [self.cv visibleCells];
//        SelectedCell * cell = [arr objectAtIndex:a];
//        [cell addSubview:demoView];
////        SelectedCell * Xcell;
//        //        NSArray *arr = [self.cv visibleCells];
//        //        SelectedCell * cell = [arr firstObject];
//                [demoView mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.edges.equalTo(cell);
//                }];
//        demoView.frame = CGRectMake(WIDTH/2-50, 200, 100, 100);
//
//    }];
//    _demoView = self.demoViews[0];
//    _demoView.hidden = YES;
//    _demoView.progressView.backgroundColor =[UIColor grayColor];
//    if (!_countLabel) {
//        _countLabel = [[UILabel alloc] init];
//        [_demoView addSubview:_countLabel];
//        //        SelectedCell * cell = [UICollectionView ]
//
//        _countLabel.backgroundColor = [UIColor redColor];
//        _countLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)_RealInteger,(long)_maxInteger];
//        [_countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(_demoView.mas_bottom).offset(30);
//            make.left.equalTo(_demoView.mas_left);
//            make.right.equalTo(_demoView.mas_right);
//            make.height.equalTo(@(40));
//        }];
//
//    }
//
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    _fallfileCount = 0;
    self.updateFileCount = 0;
    _CellCount = 0;
    _imageArrCountFall = NO;
    _LocalImgPathArr = [[NSMutableArray alloc] init];
    _picArr =[[NSMutableArray alloc]init];
    _voiceArr =[[NSMutableArray alloc]init];
    _smallUrlArray = [[NSMutableArray alloc] init];
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@str=", self.programaUrl, GETPIC];
    for (int i = 0; i<_imageMongoArr.count; i++) {
        [_smallUrlArray addObject:[NSString stringWithFormat:@"%@%@",requestUrl,[_imageMongoArr objectAtIndex:i]]];
    }
    
    
    self.imgArr = [[NSMutableArray alloc]initWithArray:_imgArrFromLastPage];
    
    //    _HD = [MBProgressHUD showHUDAddedTo:view animated:YES];
    
    UIImage * img = [UIImage imageNamed:@"image_attr_normal"];
    
    [self.imgArr addObject:img];
    
    [self createLeftNavBar];
    
    if(!_isNeedDownload){
        if (!_rightNavBtn) {
            _rightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            
            [_rightNavBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            //这里添加功能判断
            if (getEnglishLanguage()) {
                [_rightNavBtn setTitle:@"Upload" forState:UIControlStateNormal];
                _rightNavBtn.frame = CGRectMake(0, 0, 60, 23);
            }else{
                _rightNavBtn.frame = CGRectMake(0, 0, 50, 23);
                [_rightNavBtn setTitle:@"上传" forState:UIControlStateNormal];
            }

            
            //    [rightNavBtn setBackgroundImage:[UIImage imageNamed:@"图层-6"] forState:UIControlStateNormal];
            [_rightNavBtn addTarget:self action:@selector(shangchuan) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:_rightNavBtn];
            self.navigationItem.rightBarButtonItem=item;
        }
        
    }else{
        
    }
    
    
    //self.navigationItem.rightBarButtonItem.tintColor=[UIColor cyanColor];
    [self createUI];
    
    //     _timer= [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(progressSimulation:) userInfo:self repeats:YES];
    self.view.backgroundColor =[UIColor colorWithHex:0xf7f7f7];
}



- (void)createUI{
    
    if(_isNeedDownload){
        if(_imageMongoArr.count==0){
            if (!_talkView) {
                _talkView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 114)];
                _talkView.backgroundColor =[UIColor whiteColor];
                [self.view addSubview:_talkView];
            }
            
            
            UILabel *yinpin =[[UILabel alloc]init];
            [_talkView addSubview:yinpin];
            [yinpin mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_talkView.mas_top).offset(20);
                make.height.equalTo(@(15));
                make.left.equalTo(_talkView.mas_left).offset(20);
                make.width.equalTo(@(200));
            }];
            
            yinpin.textColor =[UIColor colorWithHex:0x858585];
            yinpin.font =[UIFont systemFontOfSize:15];
            
            _voiceBtn =[[D3RecordButton alloc]init];
            [_talkView addSubview:_voiceBtn];
            //这里添加功能判断
            if (getEnglishLanguage()) {
                yinpin.text = @"Audio Attachment";
                [_voiceBtn setTitle:@"Hold to talk" forState:UIControlStateNormal];
            }else{
                yinpin.text = @"音频附件列表";
                [_voiceBtn setTitle:@"按住说话" forState:UIControlStateNormal];
            }

            
            [_voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(yinpin.mas_bottom).offset(25);
                make.height.equalTo(@(72/2));
                make.width.equalTo(@(572/2));
                make.centerX.equalTo(_talkView.mas_centerX);
            }];
            [_voiceBtn initRecord:self maxtime:200];//设置录音为时间
            _voiceBtn.titleLabel.font =[UIFont systemFontOfSize:16];
            
            _voiceBtn.backgroundColor =[UIColor whiteColor];
            
            [_voiceBtn setTitleColor:[UIColor colorWithHex:0x858585] forState:UIControlStateNormal];
            [_voiceBtn setBackgroundImage:[UIImage imageNamed:@"upload_btn_normal"] forState:UIControlStateNormal];
            [_voiceBtn setBackgroundImage:[UIImage imageNamed:@"upload_btn_press"] forState:UIControlStateHighlighted];
            
            if(_voiceView==nil){
                _voiceView =[[UIImageView alloc]init];
            }
            
            [_talkView addSubview:_voiceView];
            _voiceView.image =[UIImage imageNamed:@"voice_bg"];
            [_voiceView sizeToFit];
            [_voiceView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_talkView.mas_left).offset(16.5);
                make.top.equalTo(yinpin.mas_bottom).offset(25);
            }];
            _voiceView.userInteractionEnabled = YES;
            UITapGestureRecognizer *voiceTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(voiceTap:)];
            [_voiceView addGestureRecognizer:voiceTap];
            
            if(_voiceAnim==nil){
                _voiceAnim =[[UIImageView alloc]init];
            }
            
            [_voiceView addSubview:_voiceAnim];
            _voiceAnim.animationImages = @[[UIImage imageNamed:@"111"],[UIImage imageNamed:@"112"],[UIImage imageNamed:@"113"]];
            [_voiceAnim sizeToFit];
            [ _voiceAnim mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_voiceView.mas_centerY);
                make.left.equalTo(_voiceView.mas_left).offset(20);
                make.width.equalTo(@(27/2));
                make.height.equalTo(@(33/2));
            }];
            _voiceAnim.animationDuration = 1;
            _voiceAnim.hidden = YES;
            
            _voiceimg =[[UIImageView alloc]init];
            [_voiceView addSubview:_voiceimg];
            [_voiceimg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_voiceView.mas_centerY);
                make.left.equalTo(_voiceView.mas_left).offset(20);
                make.width.equalTo(@(36/2));
                make.height.equalTo(@(34/2));
            }];
            _voiceimg.image =[UIImage imageNamed:@"voice_wifi"];
            
            if(_timela==nil){
                _timela =[[UILabel alloc]init];
            }
            [_voiceView addSubview:_timela];
            [_timela sizeToFit];
            [_timela mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(_voiceView.mas_right).offset(-10);
                make.centerY.equalTo(_voiceView.mas_centerY);
            }];
            _timela.text = @"";
            _timela.textColor =[UIColor whiteColor];
            _timela.font =[UIFont systemFontOfSize:14];
            
            if(_deleVoice==nil){
                _deleVoice =[[UIButton alloc]init];
            }
            [_talkView addSubview:_deleVoice];
            [_deleVoice sizeToFit];
            [_deleVoice mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(_talkView.mas_right).offset(-23);
                make.centerY.equalTo(_voiceView.mas_centerY);
            }];
            [_deleVoice setBackgroundImage:[UIImage imageNamed:@"voice_del"] forState:UIControlStateNormal];
            [_deleVoice addTarget:self action:@selector(deleClick:) forControlEvents:UIControlEventTouchUpInside];
            _deleVoice.hidden = YES;
            _voiceView.hidden = YES;
            
            _voiceBtn.voiceTIme = ^(float voicetime){
                _voicesecond = voicetime;
            };
            
            
            
            //            [self addProgressFrame];
            
            //    _voiceBackBtn =[UIButton buttonWithType:UIButtonTypeCustom];
            //    [self.view addSubview:_voiceBackBtn];
            //    [_voiceBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            //        make.left.equalTo(_voiceBtn.mas_right).offset(10);
            //        make.top.equalTo(self.cv.mas_bottom).offset(10);
            //        make.height.equalTo(@(35));
            //        make.width.equalTo(@(100));
            //    }];
            //    [_voiceBackBtn setTitle:@"上传音频" forState:UIControlStateNormal];
            //    [_voiceBackBtn addTarget:self action:@selector(voiceBackClick:) forControlEvents:UIControlEventTouchUpInside];
            //    _voiceBackBtn.backgroundColor =[UIColor colorWithHex:0x5da6ff];
            //    [_voiceBackBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            //    _voiceBackBtn.layer.cornerRadius = 4.5;
            //    _voiceBackBtn.titleLabel.font =[UIFont systemFontOfSize:15];
            if(_isNeedDownload){
                if(_mp3MongoArr.count>0){
                    _voiceBtn.hidden = YES;
                    _voiceView.hidden = NO;
                }else{
                    _talkView.hidden = YES;
                }
                
            }else{
                
            }
            
        }else{
            UIView * titleView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 53)];
            [self.view addSubview:titleView];
            titleView.backgroundColor = [UIColor whiteColor];
            
            UILabel *la =[[UILabel alloc]initWithFrame:CGRectMake(20, 22, WIDTH-40, 20)];
            [self.view addSubview:la];
            //这里添加功能判断
            if (getEnglishLanguage()) {
                la.text = @"Picture Attachment";
            }else{
                la.text = @"图片附件列表";
            }

            
            la.font =[UIFont systemFontOfSize:15];
            la.textColor =[UIColor colorWithHex:0x858585];
            
            //    self.MsTextView=[[UITextView alloc]initWithFrame:CGRectMake(20, 70, WIDTH-40, 80)];
            //    self.MsTextView.font = [UIFont systemFontOfSize:20];
            //    [self.view addSubview:self.MsTextView];
            //    self.MsTextView.delegate = self;
            
            
            UIView * two =[[UIView alloc]initWithFrame:CGRectMake(0, 53, KWIDTH, 200)];
            [self.view addSubview:two];
            two.backgroundColor = [UIColor whiteColor];
            
            UICollectionViewFlowLayout * fl = [[UICollectionViewFlowLayout alloc]init];
            fl.scrollDirection = UICollectionViewScrollDirectionVertical;
            
            UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
            flowLayout.minimumLineSpacing = 0;
            flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
            flowLayout.itemSize = CGSizeMake(80, 80);
            flowLayout.minimumLineSpacing = 10;
            
            
            self.cv = [[UICollectionView alloc]initWithFrame:CGRectMake(20, 0, WIDTH-40,200) collectionViewLayout:fl];
            
            
            
            self.cv.backgroundColor= [UIColor whiteColor];
            
            
            self.cv.delegate = self;
            self.cv.dataSource = self;
            
            [self.cv registerClass:NSClassFromString(@"SelectedCell") forCellWithReuseIdentifier:@"cell"];
            
            [two addSubview:self.cv];
            
            _talkView =[[UIView alloc]initWithFrame:CGRectMake(0, two.frame.origin.y+200+11, KWIDTH, 114)];
            _talkView.backgroundColor =[UIColor whiteColor];
            [self.view addSubview:_talkView];
            
            UILabel *yinpin =[[UILabel alloc]init];
            [_talkView addSubview:yinpin];
            [yinpin mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_talkView.mas_top).offset(20);
                make.height.equalTo(@(15));
                make.left.equalTo(_talkView.mas_left).offset(20);
                make.width.equalTo(@(200));
            }];
            _voiceBtn =[[D3RecordButton alloc]init];

            
            //这里添加功能判断
            if (getEnglishLanguage()) {
                yinpin.text = @"Audio Attachment";
                [_voiceBtn setTitle:@"Hold to talk" forState:UIControlStateNormal];
            }else{
                yinpin.text = @"音频附件列表";
                [_voiceBtn setTitle:@"按住说话" forState:UIControlStateNormal];
            }

            
            yinpin.textColor =[UIColor colorWithHex:0x858585];
            yinpin.font =[UIFont systemFontOfSize:15];
            
            [_talkView addSubview:_voiceBtn];
            
            [_voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(yinpin.mas_bottom).offset(25);
                make.height.equalTo(@(72/2));
                make.width.equalTo(@(572/2));
                make.centerX.equalTo(_talkView.mas_centerX);
            }];
            [_voiceBtn initRecord:self maxtime:200];//设置录音为时间
            _voiceBtn.titleLabel.font =[UIFont systemFontOfSize:16];
            
            _voiceBtn.backgroundColor =[UIColor whiteColor];
            
            [_voiceBtn setTitleColor:[UIColor colorWithHex:0x858585] forState:UIControlStateNormal];
            [_voiceBtn setBackgroundImage:[UIImage imageNamed:@"upload_btn_normal"] forState:UIControlStateNormal];
            [_voiceBtn setBackgroundImage:[UIImage imageNamed:@"upload_btn_press"] forState:UIControlStateHighlighted];
            
            if(_voiceView==nil){
                _voiceView =[[UIImageView alloc]init];
            }
            
            [_talkView addSubview:_voiceView];
            _voiceView.image =[UIImage imageNamed:@"voice_bg"];
            [_voiceView sizeToFit];
            [_voiceView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_talkView.mas_left).offset(16.5);
                make.top.equalTo(yinpin.mas_bottom).offset(25);
            }];
            _voiceView.userInteractionEnabled = YES;
            UITapGestureRecognizer *voiceTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(voiceTap:)];
            [_voiceView addGestureRecognizer:voiceTap];
            
            if(_voiceAnim==nil){
                _voiceAnim =[[UIImageView alloc]init];
            }
            
            [_voiceView addSubview:_voiceAnim];
            _voiceAnim.animationImages = @[[UIImage imageNamed:@"111"],[UIImage imageNamed:@"112"],[UIImage imageNamed:@"113"]];
            [_voiceAnim sizeToFit];
            [ _voiceAnim mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_voiceView.mas_centerY);
                make.left.equalTo(_voiceView.mas_left).offset(20);
                make.width.equalTo(@(27/2));
                make.height.equalTo(@(33/2));
            }];
            _voiceAnim.animationDuration = 1;
            _voiceAnim.hidden = YES;
            
            _voiceimg =[[UIImageView alloc]init];
            [_voiceView addSubview:_voiceimg];
            [_voiceimg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_voiceView.mas_centerY);
                make.left.equalTo(_voiceView.mas_left).offset(20);
                make.width.equalTo(@(36/2));
                make.height.equalTo(@(34/2));
            }];
            _voiceimg.image =[UIImage imageNamed:@"voice_wifi"];
            
            if(_timela==nil){
                _timela =[[UILabel alloc]init];
            }
            [_voiceView addSubview:_timela];
            [_timela sizeToFit];
            [_timela mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(_voiceView.mas_right).offset(-10);
                make.centerY.equalTo(_voiceView.mas_centerY);
            }];
            _timela.text = @"4\"";
            _timela.textColor =[UIColor whiteColor];
            _timela.font =[UIFont systemFontOfSize:14];
            
            if(_deleVoice==nil){
                _deleVoice =[[UIButton alloc]init];
            }
            [_talkView addSubview:_deleVoice];
            [_deleVoice sizeToFit];
            [_deleVoice mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(_talkView.mas_right).offset(-23);
                make.centerY.equalTo(_voiceView.mas_centerY);
            }];
            [_deleVoice setBackgroundImage:[UIImage imageNamed:@"voice_del"] forState:UIControlStateNormal];
            [_deleVoice addTarget:self action:@selector(deleClick:) forControlEvents:UIControlEventTouchUpInside];
            _deleVoice.hidden = YES;
            _voiceView.hidden = YES;
            
            _voiceBtn.voiceTIme = ^(float voicetime){
                _voicesecond = voicetime;
            };
            
            //            [self addProgressFrame];
            
            //    _voiceBackBtn =[UIButton buttonWithType:UIButtonTypeCustom];
            //    [self.view addSubview:_voiceBackBtn];
            //    [_voiceBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            //        make.left.equalTo(_voiceBtn.mas_right).offset(10);
            //        make.top.equalTo(self.cv.mas_bottom).offset(10);
            //        make.height.equalTo(@(35));
            //        make.width.equalTo(@(100));
            //    }];
            //    [_voiceBackBtn setTitle:@"上传音频" forState:UIControlStateNormal];
            //    [_voiceBackBtn addTarget:self action:@selector(voiceBackClick:) forControlEvents:UIControlEventTouchUpInside];
            //    _voiceBackBtn.backgroundColor =[UIColor colorWithHex:0x5da6ff];
            //    [_voiceBackBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            //    _voiceBackBtn.layer.cornerRadius = 4.5;
            //    _voiceBackBtn.titleLabel.font =[UIFont systemFontOfSize:15];
            if(_isNeedDownload){
                if(_mp3MongoArr.count>0){
                    _voiceBtn.hidden = YES;
                    _voiceView.hidden = NO;
                    _voiceView.hidden = YES;
                }else{
                    _talkView.hidden = YES;
                }
                
            }else{
                
            }
            
            
        }
    }else{//上传需要走的UI
        UIView * titleView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 53)];
        [self.view addSubview:titleView];
        titleView.backgroundColor = [UIColor whiteColor];
        
        UILabel *la =[[UILabel alloc]initWithFrame:CGRectMake(20, 22, WIDTH-40, 20)];
        [self.view addSubview:la];
        if ([getUserType() isEqualToString:UserISHPSTeacher]) {
            la.text = @"Picture Attachment";
        }else{
            la.text = @"图片附件列表";
        }
        la.font =[UIFont systemFontOfSize:15];
        la.textColor =[UIColor colorWithHex:0x858585];
        
        //    self.MsTextView=[[UITextView alloc]initWithFrame:CGRectMake(20, 70, WIDTH-40, 80)];
        //    self.MsTextView.font = [UIFont systemFontOfSize:20];
        //    [self.view addSubview:self.MsTextView];
        //    self.MsTextView.delegate = self;
        
        if (!_imageBGView) {
            _imageBGView =[[UIView alloc]initWithFrame:CGRectMake(0, 53, KWIDTH, 200)];
            [self.view addSubview:_imageBGView];
            _imageBGView.backgroundColor = [UIColor whiteColor];
        }
        
        
        UICollectionViewFlowLayout * fl = [[UICollectionViewFlowLayout alloc]init];
        fl.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        self.cv = [[UICollectionView alloc]initWithFrame:CGRectMake(20, 0, WIDTH-40,200) collectionViewLayout:fl];
        self.cv.backgroundColor= [UIColor whiteColor];
        
        
        self.cv.delegate = self;
        self.cv.dataSource = self;
        
        [self.cv registerClass:NSClassFromString(@"SelectedCell") forCellWithReuseIdentifier:@"cell"];
        
        [_imageBGView addSubview:self.cv];
        
        _talkView =[[UIView alloc]initWithFrame:CGRectMake(0, _imageBGView.frame.origin.y+200+11, KWIDTH, 114)];
        _talkView.backgroundColor =[UIColor whiteColor];
        [self.view addSubview:_talkView];
        
        UILabel *yinpin =[[UILabel alloc]init];
        [_talkView addSubview:yinpin];
        [yinpin mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_talkView.mas_top).offset(20);
            make.height.equalTo(@(15));
            make.left.equalTo(_talkView.mas_left).offset(20);
            make.width.equalTo(@(200));
        }];
        _voiceBtn =[[D3RecordButton alloc]init];
        //这里添加功能判断
        if (getEnglishLanguage()) {
            yinpin.text = @"Audio Attachment";
            [_voiceBtn setTitle:@"Hold to talk" forState:UIControlStateNormal];
        }else{
            yinpin.text = @"音频附件列表";
            [_voiceBtn setTitle:@"按住说话" forState:UIControlStateNormal];
        }

        
        yinpin.textColor =[UIColor colorWithHex:0x858585];
        yinpin.font =[UIFont systemFontOfSize:15];
        
        
        [_talkView addSubview:_voiceBtn];
        
        [_voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(yinpin.mas_bottom).offset(25);
            make.height.equalTo(@(72/2));
            make.width.equalTo(@(572/2));
            make.centerX.equalTo(_talkView.mas_centerX);
        }];
        [_voiceBtn initRecord:self maxtime:200];//设置录音为时间
        _voiceBtn.titleLabel.font =[UIFont systemFontOfSize:16];
        
        _voiceBtn.backgroundColor =[UIColor whiteColor];
        
        [_voiceBtn setTitleColor:[UIColor colorWithHex:0x858585] forState:UIControlStateNormal];
        [_voiceBtn setBackgroundImage:[UIImage imageNamed:@"upload_btn_normal"] forState:UIControlStateNormal];
        [_voiceBtn setBackgroundImage:[UIImage imageNamed:@"upload_btn_press"] forState:UIControlStateHighlighted];
        
        if(_voiceView==nil){
            _voiceView =[[UIImageView alloc]init];
        }
        
        [_talkView addSubview:_voiceView];
        _voiceView.image =[UIImage imageNamed:@"voice_bg"];
        [_voiceView sizeToFit];
        [_voiceView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_talkView.mas_left).offset(16.5);
            make.top.equalTo(yinpin.mas_bottom).offset(25);
        }];
        _voiceView.userInteractionEnabled = YES;
        UITapGestureRecognizer *voiceTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(voiceTap:)];
        [_voiceView addGestureRecognizer:voiceTap];
        
        if(_voiceAnim==nil){
            _voiceAnim =[[UIImageView alloc]init];
        }
        
        [_voiceView addSubview:_voiceAnim];
        _voiceAnim.animationImages = @[[UIImage imageNamed:@"111"],[UIImage imageNamed:@"112"],[UIImage imageNamed:@"113"]];
        [_voiceAnim sizeToFit];
        [ _voiceAnim mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_voiceView.mas_centerY);
            make.left.equalTo(_voiceView.mas_left).offset(20);
            make.width.equalTo(@(27/2));
            make.height.equalTo(@(33/2));
        }];
        _voiceAnim.animationDuration = 1;
        _voiceAnim.hidden = YES;
        
        _voiceimg =[[UIImageView alloc]init];
        [_voiceView addSubview:_voiceimg];
        [_voiceimg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_voiceView.mas_centerY);
            make.left.equalTo(_voiceView.mas_left).offset(20);
            make.width.equalTo(@(36/2));
            make.height.equalTo(@(34/2));
        }];
        _voiceimg.image =[UIImage imageNamed:@"voice_wifi"];
        
        if(_timela==nil){
            _timela =[[UILabel alloc]init];
        }
        [_voiceView addSubview:_timela];
        [_timela sizeToFit];
        [_timela mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_voiceView.mas_right).offset(-10);
            make.centerY.equalTo(_voiceView.mas_centerY);
        }];
        _timela.text = @"4\"";
        _timela.textColor =[UIColor whiteColor];
        _timela.font =[UIFont systemFontOfSize:14];
        
        if(_deleVoice==nil){
            _deleVoice =[[UIButton alloc]init];
        }
        [_talkView addSubview:_deleVoice];
        [_deleVoice sizeToFit];
        [_deleVoice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_talkView.mas_right).offset(-23);
            make.centerY.equalTo(_voiceView.mas_centerY);
        }];
        [_deleVoice setBackgroundImage:[UIImage imageNamed:@"voice_del"] forState:UIControlStateNormal];
        [_deleVoice addTarget:self action:@selector(deleClick:) forControlEvents:UIControlEventTouchUpInside];
        _deleVoice.hidden = YES;
        _voiceView.hidden = YES;
        
        _voiceBtn.voiceTIme = ^(float voicetime){
            _voicesecond = voicetime;
        };
        
        //        [self addProgressFrame];
        
        //    _voiceBackBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        //    [self.view addSubview:_voiceBackBtn];
        //    [_voiceBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        //        make.left.equalTo(_voiceBtn.mas_right).offset(10);
        //        make.top.equalTo(self.cv.mas_bottom).offset(10);
        //        make.height.equalTo(@(35));
        //        make.width.equalTo(@(100));
        //    }];
        //    [_voiceBackBtn setTitle:@"上传音频" forState:UIControlStateNormal];
        //    [_voiceBackBtn addTarget:self action:@selector(voiceBackClick:) forControlEvents:UIControlEventTouchUpInside];
        //    _voiceBackBtn.backgroundColor =[UIColor colorWithHex:0x5da6ff];
        //    [_voiceBackBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        //    _voiceBackBtn.layer.cornerRadius = 4.5;
        //    _voiceBackBtn.titleLabel.font =[UIFont systemFontOfSize:15];
        if(_isNeedDownload){
            if(_mp3MongoArr.count>0){
                _voiceBtn.hidden = YES;
                _voiceView.hidden = NO;
            }else{
                _talkView.hidden = YES;
            }
            
        }else{
            
        }
    }
    
    
    
    
    //    _la =[[UILabel alloc]initWithFrame:CGRectMake(100, 400, 100, 30)];
    //    [self.view addSubview:_la];
    //    _la.text = @"1";
    //
    //    self.tv =[[UITableView alloc]init];
    //    [self.view addSubview:self.tv];
    //    [self.tv mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.equalTo(self.cv.mas_bottom).offset(10);
    //        make.bottom.equalTo(self.view.mas_bottom).offset(-50);
    //        make.left.equalTo(self.view.mas_left).offset(10);
    //        make.right.equalTo(self.view.mas_right).offset(-10);
    //    }];
    //    self.tv.delegate = self;
    //    self.tv.dataSource = self;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *str = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if(cell==nil){
        cell =[[UITableViewCell alloc]
               initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    cell.textLabel.text = @"123";
    return cell;
}


-(void)deleClick:(UIButton *)btn{
    [_picArr removeAllObjects];
    _voiceBtn.hidden = NO;
    _voiceView.hidden = YES;
    _deleVoice.hidden = YES;
}

-(void)voiceTap:(UITapGestureRecognizer *)tap{
    
    if(play==nil){
        
        play = [[AVAudioPlayer alloc]initWithData:_voicedata error:nil];
        play.delegate = self;
        play.volume = 3.0f;
    }
    if(!_ifVoicing){
        _voiceimg.hidden = YES;
        _voiceAnim.hidden = NO;
        [play play];
        [_voiceAnim startAnimating];
        _ifVoicing = !_ifVoicing;
    }else{
        _voiceimg.hidden = NO;
        _voiceAnim.hidden = YES;
        [play stop];
        [_voiceAnim stopAnimating];
        _ifVoicing = !_ifVoicing;
    }
    
}

+ (NSString*)GetPathByFileName:(NSString *)_fileName ofType:(NSString *)_type{
    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];;
    NSString* fileDirectory = [[[directory stringByAppendingPathComponent:_fileName]
                                stringByAppendingPathExtension:_type]
                               stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return fileDirectory;
}



-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [_voiceAnim stopAnimating];
    _voiceAnim.hidden = YES;
    _voiceimg.hidden = NO;
}


-(void)voiceBackClick:(UIButton *)btn{
    //    play = [[AVAudioPlayer alloc]initWithData:_voicedata error:nil];
    //    play.volume = 3.0f;
    //    [play play];
    __block NSString *mp3Name;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请输入文件名" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
        
        textField.placeholder = @"文件名";
    }];
    
    UIAlertAction *action1 =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"123");
        UITextField *login = alertController.textFields.firstObject;
        mp3Name =[NSString stringWithFormat:@"%@.mp3",login.text];
        NSString *requestUrl = [NSString stringWithFormat:@"%@%@", self.programaUrl, POSTPIC];
        [NetRequest postPictures:_voicedata Url:requestUrl andFieldName:mp3Name andReturnBlock:^(NSData *progress, NSError *error) {
            
            if(!error){
                
                NSString *str =[[NSString alloc]initWithData:progress encoding:NSUTF8StringEncoding];
                NSLog(@"%@++++++++++++++++++++%d",str,a);
                _voiceString = str;
                [_picArr addObject:str];
                //                _isHaveVoice = YES;
                _picID(_picArr,nil,nil);
                [self voiceSuccess];
                
            }else{
                NSLog(@"失败");
            }
            
            
        } andFloatProsess:^(CGFloat prosess) {
            NSLog(@"%f", prosess);
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
            });
            
        }];
        
        
    }];
    [alertController addAction:action1];
    
    [self presentViewController:alertController animated:NO completion:nil];
    
}


-(void)voiceSuccess{
    
    UIAlertController *alert =[UIAlertController alertControllerWithTitle:nil message:@"上传成功" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:^{
    }];
    
    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(creatAlert2:) userInfo:alert repeats:NO];
}


-(void)endRecord:(NSData *)voiceData{
    //    NSError *error;
    
    //    play = [[AVAudioPlayer alloc]initWithData:voiceData error:&error];
    //    NSLog(@"%@",error);
    //    play.volume = 1.0f;//音量
    //    [play play];
    _voiceBtn.hidden = YES;
    _voiceView.hidden = NO;
    _deleVoice.hidden = NO;
    _voicedata = voiceData;
    _timela.text =[NSString stringWithFormat:@"%.0f\"",_voicesecond];
    [self voiceFileNameAlertview];
    //    [_voiceDataArr addObject:voiceData];
    ////    if(_voiceArr.count>0){
    ////        [_voiceArr removeAllObjects];
    ////    }
    //    NSLog(@"yesssssssssss..........%f",play.duration);
    
    
    
}
//写文件名
-(void)voiceFileNameAlertview{
    __block NSString *mp3Name;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请输入文件名" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
        
        textField.placeholder = @"文件名";
    }];
    _isHaveVoice = YES;
    UIAlertAction *action1 =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"123");
        UITextField *login = alertController.textFields.firstObject;
        mp3Name =[NSString stringWithFormat:@"%@.mp3",login.text];
        NSString *requestUrl = [NSString stringWithFormat:@"%@%@", self.programaUrl, POSTPIC];
        [NetRequest postPictures:_voicedata Url:requestUrl andFieldName:mp3Name andReturnBlock:^(NSData *progress, NSError *error) {
            
            if(!error){
                
                NSString *str =[[NSString alloc]initWithData:progress encoding:NSUTF8StringEncoding];
                NSLog(@"%@++++++++++++++++++++%d",str,a);
                _voiceString = str;
                //                _isHaveVoice = YES;
                [_picArr addObject:str];
                //                [self voiceSuccess];
                
            }else{
                NSLog(@"失败");
            }
            
            
        } andFloatProsess:^(CGFloat prosess) {
            NSLog(@"%f", prosess);
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
            });
            
        }];
        
        
    }];
    [alertController addAction:action1];
    
    [self presentViewController:alertController animated:NO completion:nil];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat w = (WIDTH-40)/4-5;
    
    return CGSizeMake(w, w);
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (_isNeedDownload) {
        return self.imageMongoArr.count;
    }
    return self.imgArr.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    SelectedCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    //NSArray *arr = self.imgArr;
    //    cell.iv.image = self.imgArr[indexPath.row];
    //[self changeAlphaOfImageWith:0.2 withImage:self.iv.image];
    NSLog(@"%@",_imgArr);
    if(!_isNeedDownload){
        cell.iv.image = self.imgArr[indexPath.row];
        //        cell.iv.alpha = 0.5;
        if(self.imgArr.count>1){
            if(indexPath.row==self.imgArr.count-1&&!_imageArrCountFall){
                NSLog(@"%@",_imgArr);
                cell.iv.highlightedImage = [UIImage imageNamed:@"image_attr_press"];
                cell.iv.userInteractionEnabled = NO;
            }else{
                cell.iv.highlightedImage = nil;
            }
        }else{
            cell.iv.highlightedImage = [UIImage imageNamed:@"image_attr_press"];
        }
    }
    if(!_isNeedDownload){
        
        if (indexPath.row != (_imageArrCountFall?self.imgArr.count:self.imgArr.count-1)) {
            
            cell.iv.userInteractionEnabled = YES;
            
            //            UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
            
            cell.iv.tag =  100+indexPath.row;
            NSLog(@"%ld",(long)indexPath.row);
            
            //            [cell.iv addGestureRecognizer:tapGesture];
            
            UILongPressGestureRecognizer* longgs=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longpress:)];
            [cell.iv addGestureRecognizer:longgs];//为cell添加手势
            longgs.minimumPressDuration=0.5;//定义长按识别时长
            longgs.view.tag=indexPath.row+1000;//将手势和cell的序号绑定
            
        }
        cell.indexPath = indexPath;
        return cell;
    }else{
        
        
        //        [cell.iv sd_setImageWithURL:[NSURL URLWithString:_smallUrlArray[indexPath.row]]];
        [cell.iv sd_setImageWithURL:[NSURL URLWithString:_smallUrlArray[indexPath.row]] placeholderImage:[UIImage imageNamed:@"loading"] options:SDWebImageRetryFailed completed:^(UIImage *image,NSError *error, SDImageCacheType cacheType,NSURL *imageURL) {
            if (error) {
                cell.iv.image = [UIImage imageNamed:@"loadfaile"];
                
            }else{
                CGSize newSize;
                
                CGImageRef imageRef =nil;
                //            UIImage *newImage = image;
                //            NSInteger i = (WIDTH-40)/4-5;
                
                if ((image.size.width / image.size.height) < 1) {
                    
                    if (newSize.height>newSize.width) {
                        newSize.height = image.size.width*1;
                        
                        newSize.width = image.size.width *1;
                        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0,fabs(image.size.width - newSize.width) / 2, newSize.width, newSize.height));
                    }else{
                        newSize.height = image.size.height*1;
                        
                        newSize.width = image.size.height *1;
                        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0,fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
                    }
                    
                    
                    
                    
                    
                    
                    
                } else {
                    
                    if (newSize.height>newSize.width) {
                        newSize.height = image.size.width*1;
                        
                        newSize.width = image.size.width *1;
                    }else{
                        newSize.height = image.size.height*1;
                        
                        newSize.width = image.size.height *1;
                    }
                    
                    
                    
                    
                    //                imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));
                    
                    
                    
                }
                
                
                NSLog(@"第一个打印%@",NSStringFromCGSize(image.size));
                NSLog(@"第一个打印%@",NSStringFromCGRect(cell.iv.bounds));
                NSLog(@"第一个打印%@",NSStringFromCGRect(cell.iv.frame));
                
                
                //            cell.iv.image =[UIImage imageWithCGImage:imageRef];
                cell.iv.image = [self OriginImage:image scaleToSize:cell.iv.bounds.size];
                
                //            CGRect frame = cell.iv.frame;
                //            frame.size = newSize;
                //            cell.iv.bounds = frame;
                NSLog(@"第一个打印%@",NSStringFromCGRect(cell.iv.bounds));
                NSLog(@"第一个打印%@",NSStringFromCGRect(cell.iv.frame));
            }
            
            
            
        }];
        cell.iv.tag = indexPath.row + 100;
        cell.iv.contentMode = UIViewContentModeScaleAspectFill;
        cell.iv.userInteractionEnabled = YES;
        
        //            UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        
        //            cell.iv.tag =  100+indexPath.row;
        NSLog(@"%ld",(long)indexPath.row);
        
        //            [cell.iv addGestureRecognizer:tapGesture];
        
        //            UILongPressGestureRecognizer* longgs=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longpress:)];
        //            [cell.iv addGestureRecognizer:longgs];//为cell添加手势
        //            longgs.minimumPressDuration=0.5;//定义长按识别时长
        //            longgs.view.tag=indexPath.row+1000;//将手势和cell的序号绑定
        
        cell.indexPath = indexPath;
        return cell;
    }
    
    
    
}
-(UIImage*)OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    //Determine whether the screen is retina
    
    /*
     *
     *
     *
     *解决图片缩小模糊的判断
     *
     *
     *
     */
    
    if([[UIScreen mainScreen] scale] == 2.0){
        UIGraphicsBeginImageContextWithOptions(size, NO, 2.0);
    }
    else if ([[UIScreen mainScreen] scale] == 3.0){
        UIGraphicsBeginImageContextWithOptions(size, NO, 3.0);
    }
    else{
        UIGraphicsBeginImageContext(size);
    }
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}


-(void)longpress:(UILongPressGestureRecognizer*)ges{
    if(ges.state==UIGestureRecognizerStateBegan){
        //获取目标cell
        if (_imgArr.count == 1) {
            return;
        }
        NSInteger row=ges.view.tag-1000;
        if (self.imgArr.count == 16&&_imageArrCountFall) {
            [self.imgArr removeObjectAtIndex:row];
            _imageArrCountFall = NO;
            [_imgArr addObject:[UIImage imageNamed:@"image_attr_normal"]];
        }else{
            [self.imgArr removeObjectAtIndex:row];
            _imageArrCountFall = NO;
        }
        [self.LocalImgPathArr removeObjectAtIndex:row];
        [self changeImageBackgroundViewAndTalkView];
        [self.cv reloadData];
        NSLog(@"%@",_imgArr);
    }
}
//行距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 5;
}
//列距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 5;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    NSLog(@"******%lu",(unsigned long)[_imgArr count]);
    if(!_isNeedDownload){
        if (indexPath.row == self.imgArr.count -1&&!_imageArrCountFall) {
            
            [self toChoose];
        }
        // 加载本地图片
        NSMutableArray *browseItemArray = [[NSMutableArray alloc]init];
        int i = 0;
        for(i = 0;i < [_imgArr count];i++)
        {
            if(i == _imgArr.count -1){
                break;
            }
            UIImageView *imageView = [self.view viewWithTag:i + 100];
            MSSBrowseModel *browseItem = [[MSSBrowseModel alloc]init];
            browseItem.bigImage = [_imgArr objectAtIndex:i];
//            browseItem.bigImageLocalPath = [_LocalImgPathArr objectAtIndex:i]; //建议传本地图片的路径来减少内存使用
            //                browseItem.bigImage = imageView.image;// 大图赋值
            browseItem.smallImageView = imageView;// 小图
            [browseItemArray addObject:browseItem];
        }
        //            MSSCollectionViewCell *cell = (MSSCollectionViewCell *)[_collectionView cellForItemAtIndexPath:indexPath];
        MSSBrowseLocalViewController *bvc = [[MSSBrowseLocalViewController alloc]initWithBrowseItemArray:browseItemArray currentIndex:indexPath.row];
        [bvc showBrowseViewController];
        
    }else{
        NSMutableArray *bigUrlArray = [[NSMutableArray alloc] init];
        NSMutableArray *browseItemArray = [[NSMutableArray alloc]init];
        NSString *requestUrl = [NSString stringWithFormat:@"%@%@str=", self.programaUrl, GETPIC];
        for (int i = 0; i<_imageMongoArr.count; i++) {
            [bigUrlArray addObject:[NSString stringWithFormat:@"%@%@",requestUrl,[_imageMongoArr objectAtIndex:i]]];
        }
        
        for(int i = 0;i < [_imageMongoArr count];i++)
        {
            
            
            UIImageView *imageView = [self.view viewWithTag:i + 100];
            MSSBrowseModel *browseItem = [[MSSBrowseModel alloc]init];
            browseItem.bigImageUrl = bigUrlArray[i];// 加载网络图片大图地址
            browseItem.smallImageView = imageView;// 小图
            [browseItemArray addObject:browseItem];
        }
        //        MSSCollectionViewCell *cell = (MSSCollectionViewCell *)[_collectionView cellForItemAtIndexPath:indexPath];
        MSSBrowseNetworkViewController *bvc = [[MSSBrowseNetworkViewController alloc]initWithBrowseItemArray:browseItemArray currentIndex:indexPath.row];
        bvc.isEqualRatio = NO;// 大图小图不等比时需要设置这个属性（建议等比）
        [bvc showBrowseViewController];
    }
    
    
    
}


- (void)toChoose{
    //    if(_imgArr.count>1){
    [_imgArr removeLastObject];
    //    }
    UIAlertController * alert;
    NSString *firstTitleStr = @"";
    NSString *secondTitleStr = @"";
    NSString *fourthTitleStr;
    NSString *message;
    //这里添加功能判断
    if (getEnglishLanguage()) {
        alert = [UIAlertController alertControllerWithTitle:@"Select" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        firstTitleStr = @"Album";
        secondTitleStr = @"camera";
        fourthTitleStr = @"Cancel";
        message = @"Allow iHampson to access your camera and microphone on Settings-privacy on your iPhone";
    }else{
        message = @"请允许该应用使用相机\n方法：设置->隐私->相机";
        firstTitleStr = @"相册";
        secondTitleStr = @"相机";
        fourthTitleStr = @"取消";
        alert = [UIAlertController alertControllerWithTitle:@"选择" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    }

    
    
    
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:firstTitleStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //        PhotoViewController * photo = [[PhotoViewController alloc]init];
        //
        //        __weak typeof(self)weakSelf = self;
        //
        //        photo.popSelectArr = ^(NSMutableArray*arr ){
        //
        //            __strong typeof(self)strongSelf = weakSelf;
        //
        //            strongSelf.imgArr = arr;
        //
        //            UIImage * img = [UIImage imageNamed:@"add-img.png"];
        //
        //            [strongSelf.imgArr addObject:img];
        //
        //            [strongSelf.cv reloadData];
        //
        //          //  NSLog(@"%ld",self.imgArr.count);
        //
        //        };
        //
        //        [self.navigationController pushViewController:photo animated:NO];
        //        NSInteger a = _imgArr.count>=7?16-_imgArr.count:9;
        //        NSLog(@"%ld",a);
        _ZJXDB = YES;
        imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:(16 - _imgArr.count) delegate:self];
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.allowPickingVideo = NO;
        __weak __typeof(self)weakSelf = self;
        NSMutableArray<NSString*> *imagePaths = [[NSMutableArray alloc] init];
        ZMView *zmView = [[ZMView alloc]init];
        [imagePickerVc setDidFinishPickingPhotosWithInfosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto,NSArray<NSDictionary *> *infos){
            
            int index = 0;
            __block NSInteger totalCount = photos.count;
            __block NSInteger curIndex = 0;
            for(NSDictionary* dic in infos){
                UIImage* photo = [photos objectAtIndex:index];
                NSURL* url = [dic objectForKey:@"PHImageFileURLKey"];
                __block NSString* path = [url absoluteString];
                PHAsset* asset = assets[index];
                [asset valueForKey:@"filename"];
                __block NSString* filename = [path lastPathComponent];
                if(filename == nil){
                    [asset requestContentEditingInputWithOptions:nil completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info){
                        NSURL* fileUrl = contentEditingInput.fullSizeImageURL;
                        filename = [[fileUrl absoluteString] lastPathComponent];
                        path = [zmView saveImageToLocalimage:photo filename:filename];
                        [imagePaths addObject:path];
                        curIndex++;
                        if(curIndex == totalCount){
                            [weakSelf sendPics:imagePaths];
                        }
                    }];
                }else{
                    path = [zmView saveImageToLocalimage:photo filename:filename];
                    UIImage *photoImg = [[UIImage alloc]initWithContentsOfFile:path];
                    //                    [imagePaths addObject:path];
                    
                    
                    [weakSelf.LocalImgPathArr addObject:path];
                    [imagePaths addObject:photoImg];
                    //                    NSLog(@"%@",_imgArr);
                    [weakSelf.imgArr addObject:photoImg];
                    if (_imgArr.count == 16) {
                        _imageArrCountFall = YES;
                    }
                    curIndex++;
                    if(curIndex == totalCount){
                        [weakSelf sendPics:imagePaths];
                    }
                }
                index++;
                
            }
            
        }];
        
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
        
    }];
    
    UIAlertAction * action2 = [UIAlertAction actionWithTitle:secondTitleStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authStatus == AVAuthorizationStatusDenied||authStatus == AVAuthorizationStatusRestricted) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alert show];
                return ;
            }
        }
        _ZJXDB = NO;
        UIImage * img = [UIImage imageNamed:@"image_attr_normal"];
        if (_imgArr.count<16) {
            [self.imgArr addObject:img];
        }
        
        UIImagePickerController *pick = [[UIImagePickerController alloc] init];
        pick.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        pick.delegate = self;
        pick.allowsEditing = YES;  //是否可编辑
        [self presentViewController:pick animated:YES completion:^{
            
        }];
        
    }];
    
    //    UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //
    //        UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    //        ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    //        NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    //        ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
    //        [self presentViewController:ipc animated:YES completion:nil];
    //        ipc.videoMaximumDuration = 30.0f;//30秒
    //        ipc.delegate = self;//设置委托
    //        NSLog(@"122");
    //    }];
    
    UIAlertAction * action4 = [UIAlertAction actionWithTitle:fourthTitleStr style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        UIImage * img = [UIImage imageNamed:@"image_attr_normal"];
        NSLog(@"%@",_imgArr);
        //        [self.imgArr removeObjectAtIndex:0];
        NSLog(@"%@",_imgArr);
        [self.imgArr addObject:img];
        [self.cv reloadData];
        
    }];
    //
    [alert addAction: action1];
    [alert addAction: action2];
    //    [alert addAction: action3];
    [alert addAction: action4];
    
    [self presentViewController:alert animated:NO completion:nil];
    
}



#pragma mark - 代理方法 通过这里可以把把图片数组传到相应的界面
-(void) sendPics:(NSMutableArray*)pics{
    if(pics.count>0){
        
        self.imagePaths = pics;
        UIImage * img = [UIImage imageNamed:@"image_attr_normal"];
        NSLog(@"%@",_imgArr);
        //        [self.imgArr removeObjectAtIndex:0];
        if (_imgArr.count <= 15) {
            
            [self.imgArr addObject:img];
        }
        
        [self changeImageBackgroundViewAndTalkView];
        [self.cv reloadData];
        NSLog(@"%@",_imgArr);
        
    }
    
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:( NSString *)kUTTypeImage]){
        
        //得到图片
        UIImage * image0 = [info objectForKey:UIImagePickerControllerOriginalImage];
        //图片存入相册
        UIImage * img = [UIImage imageNamed:@"image_attr_normal"];
        UIImageWriteToSavedPhotosAlbum(image0, nil, nil, nil);
        NSLog(@"%@",_imgArr);
        [self.imgArr removeLastObject];
        
        [self.imgArr addObject:image0];
        [self.imgArr addObject:img];
        NSLog(@"%@",_imgArr);
        [self.cv reloadData];
        [self dismissModalViewControllerAnimated:YES];
    }else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
        NSURL* mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
        
        //创建ALAssetsLibrary对象并将视频保存到媒体库
        
        
        ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
        
        // 将视频保存到相册中
        
        [assetsLibrary writeVideoAtPathToSavedPhotosAlbum:mediaURL
                                          completionBlock:^(NSURL *assetURL,NSError *error) {
                                              
                                              if (!error) {
                                                  
                                                  NSLog(@"captured video saved with no error.");
                                                  
                                              }else{
                                                  
                                                  NSLog(@"error occured while saving the video:%@", error);
                                                  
                                              }
                                              
                                          }];
        [self dismissModalViewControllerAnimated:YES];
    }
    
}


-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
    UIImage * img = [UIImage imageNamed:@"image_attr_normal"];
    NSLog(@"%@",_imgArr);
    //        [self.imgArr removeObjectAtIndex:0];
    if (_ZJXDB) {
        [self.imgArr addObject:img];
    }
    
    [self.cv reloadData];
}



- (void)tapAction:(UITapGestureRecognizer*)sender{
    
    // NSLog(@"%ld",[sender view].tag);
    UIImageView * iv = (UIImageView*)[sender view];
    
    UIImage * img = iv.image;
    NSLog(@"%ld",(long)iv.tag);
    //创建一个黑色背景
    _background = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH , HEIGHT)];
    
    [ _background setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview: _background];
    
    
    CGFloat h = WIDTH*img.size.height/img.size.width;
    // NSLog(@"h = %lf",h);
    
    //创建显示图像的视图
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (HEIGHT-h)/2, WIDTH, h)];
    //要显示的图片，即要放大的图片
    imgView.image = img;
    [ _background addSubview:imgView];
    
    imgView.userInteractionEnabled = YES;
    //添加点击手势（即点击图片后退出全屏）
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
    [imgView addGestureRecognizer:tapGesture];
    
    [self shakeToShow: _background];//放大过程中的动画
    
    //缩放手势
    UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchView:)];
    [imgView addGestureRecognizer:pinchGestureRecognizer];
    //移动手势
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panView:)];
    [imgView addGestureRecognizer:panGestureRecognizer];
    
}
//拖拽
- (void) panView:(UIPanGestureRecognizer *)panGestureRecognizer
{
    UIView *view = panGestureRecognizer.view;
    if (panGestureRecognizer.state == UIGestureRecognizerStateBegan || panGestureRecognizer.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [panGestureRecognizer translationInView:view.superview];
        [view setCenter:(CGPoint){view.center.x + translation.x, view.center.y + translation.y}];
        [panGestureRecognizer setTranslation:CGPointZero inView:view.superview];
    }
}
//缩放
- (void) pinchView:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
    UIView *view = pinchGestureRecognizer.view;
    if (pinchGestureRecognizer.state == UIGestureRecognizerStateBegan || pinchGestureRecognizer.state == UIGestureRecognizerStateChanged) {
        view.transform = CGAffineTransformScale(view.transform, pinchGestureRecognizer.scale, pinchGestureRecognizer.scale);
        pinchGestureRecognizer.scale = 1;
    }
}


-(void)closeView{
    self.navigationController.navigationBarHidden = NO;
    [_background removeFromSuperview];
}
//放大过程中出现的缓慢动画
- (void) shakeToShow:(UIView*)aView{
    
    self.navigationController.navigationBarHidden = YES;//
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.1;
    NSMutableArray *values = [NSMutableArray array];
    //  [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}

static int a = 0;
-(void)shangchuan{
    if (_imgArr.count == 1) {
        if (_picArr.count != 0) {
            NSLog(@"怪异的indexpath");
            UIAlertController *alert;
            if ([getUserType() isEqualToString:UserISHPSTeacher]) {
                alert =[UIAlertController alertControllerWithTitle:nil message:@"Uploaded" preferredStyle:UIAlertControllerStyleAlert];
            }else{
                alert =[UIAlertController alertControllerWithTitle:nil message:@"上传成功" preferredStyle:UIAlertControllerStyleAlert];
            }
            [self presentViewController:alert animated:YES completion:^{
            }];
            
            [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(creatAlert:) userInfo:alert repeats:NO];
            return;
        }

        return;
    }
    _deleVoice.userInteractionEnabled = NO;
    _rightNavBtn.userInteractionEnabled = NO;
    self.cv.userInteractionEnabled = NO;
    _voiceBtn.userInteractionEnabled = NO;
    //    NSLog(@"没服务器你传哪去");
    //    UIImage *iim = self.imgArr[0];
    
    
    if(a>(_imageArrCountFall?_imgArr.count-1:_imgArr.count-2)){
        a=0;
        _demoView.hidden = YES;
        _allProgressBackgroundView.hidden = YES;
        _countLabel.hidden = YES;
        _countBGLabel.hidden = YES;
        UIAlertController *alert;
        //这里添加功能判断
        if (getEnglishLanguage()) {
            if (_fallfileCount > 0) {
                alert =[UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"Uploaded,Failed:%ld,Please re upload",(long)_fallfileCount] preferredStyle:UIAlertControllerStyleAlert];
                _rightNavBtn.userInteractionEnabled = YES;
                return;
            }else{
                alert =[UIAlertController alertControllerWithTitle:nil message:@"Uploaded" preferredStyle:UIAlertControllerStyleAlert];
            }
        }else{
            if (_fallfileCount > 0) {
                alert =[UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"上传成功，失败%ld个，请重新上传",(long)_fallfileCount] preferredStyle:UIAlertControllerStyleAlert];
                _rightNavBtn.userInteractionEnabled = YES;
                [self presentViewController:alert animated:YES completion:^{
                }];
                
//                [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(creatAlert:) userInfo:alert repeats:NO];
                return;
            }else{
                alert =[UIAlertController alertControllerWithTitle:nil message:@"上传成功" preferredStyle:UIAlertControllerStyleAlert];
            }
        }

        
        
        
        [self presentViewController:alert animated:YES completion:^{
        }];
        
        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(creatAlert:) userInfo:alert repeats:NO];
        return;
        
    }
    if(self.imgArr.count>1){
        NSLog(@"@@@@@@@%lu",(unsigned long)self.imgArr.count);
        //if(self.imgArr.count>1){
        //for(int i=0;i<[self.imgArr count];i++){
        UIImage *iiimm = self.imgArr[a];
        NSArray *arr = [self.cv visibleCells];
        //        SelectedCell * cell = [arr objectAtIndex:a];
        SelectedCell * Xcell;
        if (a == 0) {//
            for (SelectedCell * cell in arr) {
                NSLog(@"怪异的indexpath : %zd",cell.indexPath.row);
                if (cell.indexPath.row == a) {
                    Xcell = cell;
                    cell.bgLabel.hidden = YES;
                    //                    break;
                }else{
                    if (a == 0) {//第一次进入循环
                        if (cell.indexPath.row != arr.count-1) {//除了正在上传和已上传完成的还有最后一个外，设置图片透明度为0.6
                            cell.iv.alpha = 0.6;
                        }else{//最后一个是不透明的
                            if (_imgArr.count == 16) {
                                cell.iv.alpha = 0.6;
                            }else{
                                cell.iv.alpha = 1;
                            }
                            
                        }
                        
                        
                        //                        cell.bgLabel.hidden = NO;
                    }
                }
            }
            
            
            [self CreateALabelForProgress];
            
        }else{
            for (SelectedCell * cell in arr) {
                NSLog(@"怪异的indexpath : %zd",cell.indexPath.row);
                if (cell.indexPath.row == a) {
                    Xcell = cell;
                    break;
                }
            }
        }
        if (Xcell) {
            Xcell.demoView.hidden = NO;
            Xcell.demoView.alpha = 0.5;
            Xcell.iv.alpha = 1;
        }
        
        
        
        
        NSData *imageData = UIImagePNGRepresentation(iiimm);
        _demoView.hidden = NO;
        _RealInteger = a+1;
        if (_imageArrCountFall == NO) {
            _maxInteger = self.imgArr.count - 1;
        }else{
            _maxInteger = self.imgArr.count;
        }
        
        //        _countLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)_RealInteger,(long)_maxInteger];
        
        NSString *requestUrl = [NSString stringWithFormat:@"%@%@", self.programaUrl, POSTPIC];
        [NetRequest postPictures:imageData Url:requestUrl andFieldName:[NSString stringWithFormat:@"%d图片",a+1] andReturnBlock:^(NSData *progress, NSError *error) {
            
            if(!error){
                
                NSString *str =[[NSString alloc]initWithData:progress encoding:NSUTF8StringEncoding];
                NSLog(@"%@++++++++++++++++++++%d",str,a);
                _picString = str;
                [_picArr addObject:str];
                
            }else{
                NSLog(@"上传huashi失败");
                [self.failedSaveCountArray addObject:[NSString stringWithFormat:@"%d",a]];
                NSLog(@"%@",_failedSaveCountArray);
                _fallfileCount ++;
                if (Xcell) {
                    Xcell.demoView.hidden  = YES;
                    Xcell.iv.alpha = 1;
                }
                NSString *failMessage = @"";
                //这里添加功能判断
                if (getEnglishLanguage()) {
                    failMessage = @"Upload failed, please upload again";
                }else{
                    failMessage = @"上传失败，请重新上传";
                }

                UIAlertController *alert =[UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"%@",failMessage] preferredStyle:UIAlertControllerStyleAlert];
                _deleVoice.userInteractionEnabled = YES;
                _rightNavBtn.userInteractionEnabled = YES;
                self.cv.userInteractionEnabled = YES;
                _voiceBtn.userInteractionEnabled = YES;
                _allProgressBackgroundView.hidden = YES;
                [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dismissAlertController:) userInfo:alert repeats:NO];
                
                [self presentViewController:alert animated:YES completion:^{
                }];
                a = 0;
                _fallfileCount = 0;
                _updateFileCount = 0;
                return ;
            }
            a++;
            
            
            
            
            
            
            sss = (float)a/(float)(_imgArr.count-1);
            //            _demoView.progressView.progress = sss;
            [self shangchuan];
            
            
        } andFloatProsess:^(CGFloat prosess) {
            NSLog(@"%f", prosess);
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
                _allProgressBackgroundView.hidden = NO;
                if (Xcell) {
                    Xcell.demoView.progressView.progress = prosess;
                }
                if (prosess > 0.99) {
                    
                    Xcell.bgLabel.hidden = YES;
                    Xcell.iv.alpha = 1;
                    NSLog(@"都上传完了：a%d>?_imgArr.count%lu",a,_imgArr.count-3);
                    if (a>_imgArr.count-3) {//都传完了隐藏进度
                        _allProgressBackgroundView.hidden = YES;
                        _countLabel.hidden = YES;
                        _countBGLabel.hidden = YES;
                    }
                }
                [self ChangeProgress:prosess];
                
            });
            
        }];
        
    }
    
    
}


- (void)dismissAlertController:(NSTimer *)timer{
    UIAlertController *alert = [timer userInfo];
    
    [alert dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [_picArr removeAllObjects];
    alert = nil;
}

- (void)progressSimulation:(CGFloat )pro
{
    static CGFloat progress = 0;
    
    if (progress < 1.0) {
        progress += 0.01;
        
        // 循环
        if (progress >= 1.0){
            progress = 0;
            [self.timer invalidate];
            //这行代码很关键
            _timer=nil;
        }
        
        _la.text = [NSString stringWithFormat:@"%f",progress];
    }
}

-(void)shangchuanmany:(NSData *)data{
    
    NSString *requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, POSTPIC];
    [NetRequest postPictures:data Url:requestStr andFieldName:self.MsTextView.text andReturnBlock:^(NSData *progress, NSError *error) {
        if(!error){
            NSString *str =[[NSString alloc]initWithData:progress encoding:NSUTF8StringEncoding];
            NSLog(@"######");
            _picString = str;
            //拉克丝将登陆发酵饲料的咖啡机
        }else{
            NSLog(@"失败");
        }
        
        
        
    } andFloatProsess:^(CGFloat prosess) {
        
    }];
    
}

#pragma mark - UITextView Delegate Methods
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}


- (void)creatAlert2:(NSTimer *)timer{
    
    UIAlertController *alert = [timer userInfo];
    
    [alert dismissViewControllerAnimated:YES completion:nil];
    
    alert = nil;
    [self.navigationController popViewControllerAnimated:YES];
    
    
}

- (void)creatAlert:(NSTimer *)timer{
    
    UIAlertController *alert = [timer userInfo];
    
    [alert dismissViewControllerAnimated:YES completion:nil];
    
    alert = nil;
    [self.navigationController popViewControllerAnimated:YES];
    
    NSMutableArray *imgArrs = [[NSMutableArray alloc]initWithArray:_imgArr];
    [imgArrs removeLastObject];
    _picID(_picArr, imgArrs,_LocalImgPathArr);
    
}
- (void)ChangeProgress:(CGFloat)progress{
    if (_countLabel) {
        //        [UIView animateWithDuration:1 animations:^{
        //            [_countLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        //                make.width.equalTo(@(_RealInteger/_maxInteger*(KWIDTH - 40)));
        //            }];
        CGRect frame = _countLabel.frame;
        NSLog(@"%zd",KWIDTH);
        float i =((progress+_updateFileCount)/_maxInteger)*self.countBGLabel.frame.size.width;
        
        frame.size.width = i;
        //        [UIView animateWithDuration:0.5 animations:^{
        _countLabel.frame = frame;
        //        }];
        //        }];
        if (_RealInteger == _maxInteger&&progress>0.99) {
            
            _countLabel.hidden = YES;
            _countBGLabel.hidden = YES;
        }else{
            _countLabel.hidden = NO;
            _countBGLabel.hidden = NO;
        }
        if (progress == 1) {
            _updateFileCount ++;
        }
        if (_contentLabel) {
            if (_isHaveVoice) {
                //这里添加功能判断
                if (getEnglishLanguage()) {
                    _contentLabel.text = [NSString stringWithFormat:@"Finished %ld/%1.0f pics uploaded, audio has been uploaded",(long)_updateFileCount,_maxInteger];
                }else{
                    _contentLabel.text = [NSString stringWithFormat:@"已完成 %ld/%1.0f 张图片，音频已上传成功",(long)_updateFileCount,_maxInteger];
                }

                
            }else{
                if ([getUserType() isEqualToString:UserISHPSTeacher]) {
                    _contentLabel.text = [NSString stringWithFormat:@"Finished %ld/%1.0f pics uploaded",(long)_updateFileCount,_maxInteger];
                }else{
                    _contentLabel.text = [NSString stringWithFormat:@"已完成 %ld/%1.0f 张图片",(long)_updateFileCount,_maxInteger];
                }
            }
        }
        
    }else{
        [self CreateALabelForProgress];
        //        [self ChangeProgress];
    }
}

- (void)CreateALabelForProgress{
    if (!_allProgressBackgroundView) {
        _allProgressBackgroundView = [[UIView alloc] init];
        _allProgressBackgroundView.backgroundColor = [UIColor colorWithHex:0xffffff];
        [self.view addSubview:_allProgressBackgroundView];
        [_allProgressBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom);
            make.height.equalTo(@(110/2));
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
        }];
        UIView *progressLineView = [[UIView alloc] init];
        progressLineView.backgroundColor = [UIColor colorWithHex:0xd0d0d0];
        [self.allProgressBackgroundView addSubview:progressLineView];
        [progressLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_allProgressBackgroundView.mas_top);
            make.height.equalTo(@(1));
            make.left.equalTo(_allProgressBackgroundView.mas_left);
            make.right.equalTo(_allProgressBackgroundView.mas_right);
        }];
        
    }
    
    
    if (!_countBGLabel) {
        _countBGLabel = [[UILabel alloc] init];
        _countBGLabel.backgroundColor = [UIColor colorWithHex:0xbdbdbd];
        _countBGLabel.layer.masksToBounds = YES;
        _countBGLabel.layer.cornerRadius = 4.0f;
        //        _countBGLabel.layer.borderWidth = 1.0f;
        //        _countBGLabel.layer.borderColor = [UIColor blackColor].CGColor;
        [_allProgressBackgroundView addSubview:_countBGLabel];
        //        _countBGLabel.frame = CGRectMake(34/2, KHEIGHT-40-64-110/2+64/2, KWIDTH-34, 14/2);
        [_countBGLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_allProgressBackgroundView.mas_top).offset(64/2);
            make.left.equalTo(_allProgressBackgroundView.mas_left).offset(34/2);
            make.right.equalTo(_allProgressBackgroundView.mas_right).offset(-34/2);
            make.height.equalTo(@(14/2));
        }];
        
        
        
    }
    
    if (!_countLabel) {
        _countLabel = [[UILabel alloc] init];
        _countLabel.backgroundColor = [UIColor colorWithHex:0xef5152];
        //        _countLabel.layer.borderColor = [UIColor ]
        _countLabel.layer.masksToBounds = YES;
        _countLabel.layer.cornerRadius = 4.0f;
        //        _countLabel.layer.borderWidth = 1.0f;
        //        _countLabel.layer.borderColor = [UIColor blackColor].CGColor;
        [_allProgressBackgroundView addSubview:_countLabel];
        [_countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(_countBGLabel);
        }];
        
        //        CGRect frame = _countBGLabel.frame;
        //        frame.size.width = 0;
        //        _countLabel.frame = frame;
        //      _countBGLabel.layer.borderWidth = 1.0f;
    }
    
    if (!_contentLabel) {
        _contentLabel = [[UILabel alloc] init];
        [_allProgressBackgroundView addSubview:_contentLabel];
        _contentLabel.textColor = [UIColor colorWithHex:0x858585];
        _contentLabel.font = [UIFont systemFontOfSize:24/2];
        [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_allProgressBackgroundView.mas_top).offset(22/2);
            make.left.equalTo(_allProgressBackgroundView.mas_left).offset(34/2);
            make.right.equalTo(_allProgressBackgroundView.mas_right).offset(-34/2);
            make.height.equalTo(@(24/2));
        }];
        if (_isHaveVoice) {
            //这里添加功能判断
            if (getEnglishLanguage()) {
                _contentLabel.text = [NSString stringWithFormat:@"Finished 0/%1.0f pics，audio has been uploaded",_maxInteger];
            }else{
                _contentLabel.text = [NSString stringWithFormat:@"已完成 0/%1.0f 张图片，音频已上传成功",_maxInteger];
            }

            
        }else{
            //这里添加功能判断
            if (getEnglishLanguage()) {
                _contentLabel.text = [NSString stringWithFormat:@"Finished 0/%1.0f pics uploaded",_maxInteger];
            }else{
                _contentLabel.text = [NSString stringWithFormat:@"已完成 0/%1.0f 张图片",_maxInteger];
            }

            
        }
        
    }
    
}

- (void)changeImageBackgroundViewAndTalkView{
    CGFloat imageCount = _imgArr.count;
    CGFloat w = (WIDTH-40)/4-5;
    if (imageCount>8) {
        //        [_imageBGView mas_updateConstraints:^(MASConstraintMaker *make) {
        //            make.height.equalTo(@((w+5)*ceil(imageCount/4)));
        //        }];
        CGRect frame = _imageBGView.frame;
        CGFloat nmb = imageCount/4;
        NSInteger ceilCount = ceil(nmb);
        frame.size.height =(w+5)*ceilCount;
        _imageBGView.frame = frame;
        CGRect collFrame = self.cv.frame;
        collFrame.size.height = (w+5)*ceil(imageCount/4);
        _cv.frame = collFrame;
        
        _talkView.frame =CGRectMake(0, _imageBGView.frame.origin.y+_imageBGView.frame.size.height+11, KWIDTH, 114);
        
        
    }else{
        CGRect frame = _imageBGView.frame;
//        CGFloat nmb = imageCount/4;
//        NSInteger ceilCount = ceil(nmb);
        frame.size.height =200;
        _imageBGView.frame = frame;
        CGRect collFrame = self.cv.frame;
        collFrame.size.height = 200;
        _cv.frame = collFrame;
        _talkView.frame =CGRectMake(0, _imageBGView.frame.origin.y+_imageBGView.frame.size.height+11, KWIDTH, 114);
        return;
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//封存代码 (没写完)
//-(void)shangchuanFailedimage{
//    _deleVoice.userInteractionEnabled = NO;
//    _rightNavBtn.userInteractionEnabled = NO;
//    self.cv.userInteractionEnabled = NO;
//    _voiceBtn.userInteractionEnabled = NO;
//    //    NSLog(@"没服务器你传哪去");
//    //    UIImage *iim = self.imgArr[0];
//
//
//    if(_failedSaveCountArray.count == 0){
////        a=0;
//        _demoView.hidden = YES;
//        UIAlertController *alert;
//        //这里添加了角色判断   没用
//        if ([getUserType() isEqualToString:UserISHPSTeacher]) {
//            if (_fallfileCount > 0) {
//                alert =[UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"Uploaded，Failed:%ld",(long)_fallfileCount] preferredStyle:UIAlertControllerStyleAlert];
//            }else{
//                alert =[UIAlertController alertControllerWithTitle:nil message:@"Uploaded" preferredStyle:UIAlertControllerStyleAlert];
//            }
//        }else{
//            if (_fallfileCount > 0) {
//                alert =[UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"上传成功，失败%ld个",(long)_fallfileCount] preferredStyle:UIAlertControllerStyleAlert];
//            }else{
//                alert =[UIAlertController alertControllerWithTitle:nil message:@"上传成功" preferredStyle:UIAlertControllerStyleAlert];
//            }
//        }
//
//
//
//
//        [self presentViewController:alert animated:YES completion:^{
//        }];
//
//        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(creatAlert:) userInfo:alert repeats:NO];
//        return;
//
//    }
//    if(_failedSaveCountArray.count>=1){
//        NSLog(@"@@@@@@@%lu",(unsigned long)self.imgArr.count);
//        //if(self.imgArr.count>1){
//        //for(int i=0;i<[self.imgArr count];i++){
//        NSInteger index = [[_failedSaveCountArray firstObject] integerValue];
//        UIImage *iiimm;
//        if (_imgArr.count >index) {
//            iiimm = self.imgArr[index];
//        }else{
//            NSLog(@"失败文件个数取错了");
//            return;
//        }
//        NSArray *arr = [self.cv visibleCells];
//        //        SelectedCell * cell = [arr objectAtIndex:a];
//        SelectedCell * Xcell;
//        if (index == 0) {//
//            for (int i = 0; i<_failedSaveCountArray.count; i++) {
//                for (SelectedCell * cell in arr) {
//                    NSLog(@"怪异的indexpath : %zd",cell.indexPath.row);
//                    if (cell.indexPath.row == [[_failedSaveCountArray objectAtIndex:i] intValue]) {
//                        if (i == 0) {
//                           Xcell = cell;
//                        }
//                        cell.iv.alpha = 0.6;
//                        cell.bgLabel.hidden = YES;
//                        //                    break;
//                    }
////                        else{
////                        if (index == 0) {//第一次进入循环
////                            if (cell.indexPath.row != arr.count-1) {//除了正在上传和已上传完成的还有最后一个外，设置图片透明度为0.6
////                                cell.iv.alpha = 0.6;
////                            }else{//最后一个是不透明的
////                                if (_imgArr.count == 16) {
////                                    cell.iv.alpha = 0.6;
////                                }else{
////                                    cell.iv.alpha = 1;
////                                }
////
////                            }
////
////
////                            //                        cell.bgLabel.hidden = NO;
////                        }
////                    }
//                }
//            }
//
//
//            [self CreateALabelForProgress];
//
//        }else{
//            for (SelectedCell * cell in arr) {
//                NSLog(@"怪异的indexpath : %zd",cell.indexPath.row);
//                if (cell.indexPath.row == a) {
//                    Xcell = cell;
//                    break;
//                }
//            }
//        }
//        if (Xcell) {
//            Xcell.demoView.hidden = NO;
//            Xcell.demoView.alpha = 0.5;
//            Xcell.iv.alpha = 1;
//        }
//
//
//
//
//        NSData *imageData = UIImagePNGRepresentation(iiimm);
//        _demoView.hidden = NO;
//        _RealInteger = a+1;
//        if (_imageArrCountFall == NO) {
//            _maxInteger = self.imgArr.count - 1;
//        }else{
//            _maxInteger = self.imgArr.count;
//        }
//
//        //        _countLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)_RealInteger,(long)_maxInteger];
//
//        NSString *requestUrl = [NSString stringWithFormat:@"%@%@", self.programaUrl, POSTPIC];
//        [NetRequest postPictures:imageData Url:requestUrl andFieldName:[NSString stringWithFormat:@"%d图片",a+1] andReturnBlock:^(NSData *progress, NSError *error) {
//
//            if(!error){
//
//                NSString *str =[[NSString alloc]initWithData:progress encoding:NSUTF8StringEncoding];
//                NSLog(@"%@++++++++++++++++++++%d",str,a);
//                _picString = str;
//                [_picArr addObject:str];
//
//            }else{
//                NSLog(@"失败");
//                [self.failedSaveCountArray addObject:[NSString stringWithFormat:@"%d",a]];
//                NSLog(@"%@",_failedSaveCountArray);
//                _fallfileCount ++;
//                if (Xcell) {
//                    Xcell.demoView.hidden  = YES;
//                    Xcell.iv.alpha = 1;
//                }
//
//            }
//            a++;
//
//
//
//
//
//
//            sss = (float)a/(float)(_imgArr.count-1);
//            //            _demoView.progressView.progress = sss;
//            [self shangchuan];
//
//
//        } andFloatProsess:^(CGFloat prosess) {
//            NSLog(@"%f", prosess);
//            dispatch_sync(dispatch_get_main_queue(), ^{
//                //Update UI in UI thread here
//
//                if (Xcell) {
//                    Xcell.demoView.progressView.progress = prosess;
//                }
//                if (prosess > 0.99) {
//
//                    Xcell.bgLabel.hidden = YES;
//                    Xcell.iv.alpha = 1;
//                    if (a>_imgArr.count-3) {//都传完了隐藏进度
//                        _allProgressBackgroundView.hidden = YES;
//                        _countLabel.hidden = YES;
//                        _countBGLabel.hidden = YES;
//                    }
//                }
//                [self ChangeProgress:prosess];
//
//            });
//
//        }];
//
//    }
//
//
//}



@end
